package com.hao.tool.extra.cloud.module.ali.fac;

import com.hao.tool.common.util.HttpClientUtil;
import com.hao.tool.common.util.JsonKitUtil;
import com.hao.tool.extra.cloud.module.ali.entity.TextOcrDTO;
import com.hao.tool.extra.cloud.module.ali.entity.TextOcrResult;

import java.util.HashMap;

/**
 * description
 *
 * @author HaoZ on CMHK.hainan
 * @date 2021/6/10 下午5:28
 */
public class AlTextOcrFactory {


    private AlAccessToken alAccessToken;
    private Integer type;

    private final static String postUrl = "https://ocrapi-advanced.taobao.com/ocrservice/advanced";

    public AlTextOcrFactory(AlAccessToken alAccessToken, Integer type) {
        this.alAccessToken = alAccessToken;
        this.type = type;
    }

    public TextOcrResult ocrImage(String img, String imgUrl) {
        TextOcrDTO textOcrDTO = new TextOcrDTO();
        textOcrDTO.setImg(img)
                .setUrl(imgUrl);
        String appCode = alAccessToken.getAppCode();
        HashMap<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json;charset=UTF-8");
        //如果需要使用本地图片，需要将图片base64码放在img后面，如果使用网络图片，则需要将网络图片url放于url参数后面
        String bodyS = JsonKitUtil.getString(textOcrDTO);
        String response = "";
        try {
            response = HttpClientUtil.build().setHeaders(headers).sendPostFromRow(postUrl, bodyS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        TextOcrResult result = JsonKitUtil.getObject(response, TextOcrResult.class);
        return result;
    }
}
